<script setup>
import { ref, reactive, onMounted, nextTick, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 使用自定义封装的 myaxios
import { get, post } from '@/myaxios' // 修改点：替换为自己的封装方法

/**删除功能 */
const deleteFormOpen = (currentRow) => {
    ElMessageBox.confirm(
        `确定要删除 ID为[ ${currentRow.giftId}-${currentRow.giftName} ]的礼物数据么`,
        '注意',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            operationData("gift/delete", { giftId: currentRow.giftId })
        })
        .catch(() => {
            console.log("取消删除")
        })
}

/**修改功能 */
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = reactive({
    editData: {
        giftId: '',
        giftName: '',
        giftPrice: '',
        giftRatio: '',
        giftLogo: ''
    }
})

const editFormSubmit = async () => {
    editDialogVisible.value = false
    operationData("gift/edit", editForm.editData)
}

const editFormOpen = (currentRow) => {
    editDialogVisible.value = true
    get("gift/getGiftById", { giftId: currentRow.giftId }) // 修改点：使用 get 请求
        .then(resp => {
            if (resp.data.code === 2000) {
                editForm.editData = resp.data.returnData
            }
        })
}

//上传功能
const myUpload2 = (rawFile) => {
    let currentFile = rawFile.file
    let myFormData = new FormData()
    myFormData.append('myfile', currentFile)
    myFormData.append('folderName', 'gift')
    post("/headImgUpload", myFormData) // 修改点：使用 post 请求
        .then(resp => {
            ElMessage.success(resp.data.msg)
            editForm.editData.giftLogo = resp.data.returnData
        })
}

/**添加功能 */
const addDialogVisible = ref(false)
const addFormRef = ref()
const addForm = reactive({
    giftName: '',
    giftPrice: 0,
    giftRatio: 70,
    giftLogo: '',
    customerRemark: ''
})

const addFormSubmit = async () => {
    addDialogVisible.value = false
    operationData("gift/add", addForm)
}

const addFormOpen = () => {
    addDialogVisible.value = true
    nextTick(() => {
        addFormRef.value.resetFields()
    })
}

const beforeAvatarUpload = (rawFile) => {
    if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件不能超过2M')
        return false
    }
    return true
}

//上传功能
const myUpload = (rawFile) => {
    let currentFile = rawFile.file
    let myFormData = new FormData()
    myFormData.append('myfile', currentFile)
    myFormData.append('folderName', 'gift')
    post("/headImgUpload", myFormData) // 修改点：使用 post 请求
        .then(resp => {
            ElMessage.success(resp.data.msg)
            addForm.giftLogo = resp.data.returnData
        })
}

/**查询列表数据 */
const tableRef = ref()
const queryFormRef = ref()
const tableList = reactive({
    tableData: []
})
const queryForm = reactive({
    giftName: ''
})

const onSubmit = () => {
    queryData(queryForm)
}

const onReset = () => {
    queryFormRef.value.resetFields()
    queryData({})
}

/**
 * 分页组件
 */
const pageInfo = reactive({
    pageData: {
        page: 1,
        pageSize: 10,
        total: 77
    }
})

const handleCurrentChange = (val) => {
    pageInfo.pageData.page = val
    let paramsObj = { ...pageInfo.pageData, ...queryForm }
    queryData(paramsObj)
}

const handleSizeChange = (val) => {
    pageInfo.pageData.page = 1
    pageInfo.pageData.pageSize = val
    let paramsObj = { ...pageInfo.pageData, ...queryForm }
    queryData(paramsObj)
}

/**
 * 公共函数
 */
const queryData = async (params) => {
    const resp = await get("gift/query", params) // 修改点：使用 get 请求
    console.log(resp);
    if (resp.data.code === 2000) {
        tableList.tableData = resp.data.returnData
        pageInfo.pageData = resp.data.pageInfo
    } else if (resp.data.code === 2001) {
        tableList.tableData = []
        pageInfo.pageData = { page: 1, pageSize: 10, total: 0 }
    }
}

const operationData = async (url, params) => {
    const resp = await post(url, params) // 修改点：使用 post 请求
    if (resp.data.code === 2010) {
        ElMessage.success(resp.data.msg)
    } else if (resp.data.code === 2011) {
        ElMessage.error(resp.data.msg)
    }
    let paramsObj = { ...pageInfo.pageData, ...queryForm }
    await queryData(paramsObj)
}

onMounted(() => {
    queryData({})
})
</script>

<template>
    <el-form ref="queryFormRef" :inline="true" :model="queryForm">
        <el-form-item label="礼物名称" prop="giftName">
            <el-input v-model="queryForm.giftName" placeholder="giftName" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" plain @click="onSubmit">查询</el-button>
            <el-button type="primary" plain @click="onReset">重置</el-button>
            <el-button type="primary" plain @click="addFormOpen">添加</el-button>

        </el-form-item>
    </el-form>
    <el-table height="500px" ref="tableRef" :data="tableList.tableData" style="width: 100%">
        <el-table-column prop="giftId" label="ID" width="180"></el-table-column>
        <el-table-column prop="giftName" label="礼物名称" width="180"></el-table-column>
        <el-table-column prop="giftPrice" label="礼物价格" width="180">
            <template #default="scope">
                <el-tag>￥{{ scope.row.giftPrice }}</el-tag>
            </template>

        </el-table-column>
        <el-table-column prop="giftLogo" label="礼物图片" width="180">
            <template #default="scope">
                <img :src="scope.row.giftLogo">
            </template>
        </el-table-column>
        <el-table-column prop="giftRatio" label="礼物折算" width="180">
            <template #default="scope">
                <el-tag>{{ scope.row.giftRatio }}%</el-tag>
            </template>
        </el-table-column>

        <el-table-column label="操作" width="180">
            <template #default="scope">
                <el-button type="primary" plain size="small" @click="editFormOpen(scope.row)">编辑</el-button>
                <el-button type="primary" plain size="small" @click="deleteFormOpen(scope.row)">删除</el-button>
            </template>
        </el-table-column>

    </el-table>

    <el-pagination v-model:current-page="pageInfo.pageData.page" v-model:page-size="pageInfo.pageData.pageSize"
        :page-sizes="[10, 20, 30]" layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.pageData.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />

      <!-- 添加对话框 -->
  <el-dialog v-model="addDialogVisible" title="添加" width="500">
    <el-form ref="addFormRef" :model="addForm" label-width="auto" style="max-width: 400px">

      <el-form-item label="礼物名称" prop="giftName">
        <el-input v-model="addForm.giftName" placeholder="giftName" />
      </el-form-item>
      <el-form-item label="礼物单价" prop="giftPrice">
        <!-- <el-input v-model="addForm.giftPrice" placeholder="giftPrice" /> -->
        <el-input-number style="width: 100%;" v-model="addForm.giftPrice" :precision="2" :step="1" :max="1000" :min="0" />
      </el-form-item>
      <el-form-item label="礼物折算" prop="giftRatio">
        <!-- <el-input v-model="addForm.giftRatio" placeholder="giftRatio" /> -->
        <el-input-number style="width: 100%;" v-model="addForm.giftRatio" :precision="2" :step="10" :max="100" :min="0" />
      </el-form-item>
      <el-form-item label="礼物图片" prop="giftLogo">
        <!-- <el-input v-model="addForm.giftLogo" placeholder="giftLogo" /> -->
        <el-upload
        class="avatar-uploader"
        action=""
        :show-file-list="false"
        :http-request="myUpload"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="addForm.giftLogo" :src="addForm.giftLogo" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>


      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addFormSubmit">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改" width="500">
    <el-form ref="editFormRef" :model="editForm.editData" label-width="auto" style="max-width: 400px">

    <el-form-item label="礼物编号" prop="giftId">
        <el-input v-model="editForm.editData.giftId" disabled placeholder="giftId" />
      </el-form-item>
    <el-form-item label="礼物名称" prop="giftName">
        <el-input v-model="editForm.editData.giftName" placeholder="giftName" />
      </el-form-item>
      <el-form-item label="礼物单价" prop="giftPrice">
        <!-- <el-input v-model="addForm.giftPrice" placeholder="giftPrice" /> -->
        <el-input-number style="width: 100%;" v-model="editForm.editData.giftPrice" :precision="2" :step="1" :max="1000" :min="0" />
      </el-form-item>
      <el-form-item label="礼物折算" prop="giftRatio">
        <!-- <el-input v-model="addForm.giftRatio" placeholder="giftRatio" /> -->
        <el-input-number style="width: 100%;" v-model="editForm.editData.giftRatio" :precision="2" :step="10" :max="100" :min="0" />
      </el-form-item>
      <el-form-item label="礼物图片" prop="giftLogo">
        <!-- <el-input v-model="editForm.editData.giftLogo" placeholder="giftLogo" /> -->
        <el-upload
        class="avatar-uploader"
        action=""
        :show-file-list="false"
        :http-request="myUpload2"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="editForm.editData.giftLogo" :src="editForm.editData.giftLogo" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>


    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editFormSubmit">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>


</template>

<style scoped>
  tbody img{
    width: 50px;
    height: 50px;
  }
  .query-form .el-input {
  --el-input-width: 220px;
  }

  .query-form .el-select {
    --el-select-width: 220px;
  }

  /* div.el-date-editor.el-input, .el-date-editor.el-input__wrapper{
    width: 100%;
  } */
  .avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>